import axios from 'axios';
import authService from './authService';

const API_URL = 'http://localhost:8080/api/';

// 医生相关API (医生角色使用)
const getDoctorProfile = () => {
    // 直接从localStorage获取token，绕过authService
    const user = JSON.parse(localStorage.getItem('user'));
    console.log('直接从localStorage获取的用户信息:', user);
    
    const token = user && user.token ? user.token : '';
    console.log('直接获取的token:', token);
    
    const headers = { 
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
    };
    console.log('直接构建的请求头:', headers);
    
    return axios.get(API_URL + 'doctors/profile', { headers });
};

const updateDoctorProfile = (doctorData) => {
    // 直接从localStorage获取token，绕过authService
    const user = JSON.parse(localStorage.getItem('user'));
    const token = user && user.token ? user.token : '';
    
    return axios.put(API_URL + 'doctors/profile', doctorData, { 
        headers: {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json'
        }
    });
};

// 管理员相关API (管理员角色使用)
const getAllDoctors = () => {
    return axios.get(API_URL + 'admin/doctors', { headers: getAuthHeader() });
};

const getDoctorById = (id) => {
    return axios.get(API_URL + `admin/doctors/${id}`, { headers: getAuthHeader() });
};

const createDoctor = (doctorData) => {
    return axios.post(API_URL + 'admin/doctors', doctorData, { 
        headers: {
            ...getAuthHeader(),
            'Content-Type': 'application/json'
        }
    });
};

const updateDoctor = (id, doctorData) => {
    return axios.put(API_URL + `admin/doctors/${id}`, doctorData, { 
        headers: {
            ...getAuthHeader(),
            'Content-Type': 'application/json'
        }
    });
};

const deleteDoctor = (id) => {
    return axios.delete(API_URL + `admin/doctors/${id}`, { headers: getAuthHeader() });
};

const getDoctorsByDepartment = (departmentId) => {
    return axios.get(API_URL + `admin/doctors/department/${departmentId}`, { headers: getAuthHeader() });
};

// 获取JWT令牌 (为管理员接口保留)
const getAuthHeader = () => {
    const user = JSON.parse(localStorage.getItem('user'));
    if (user && user.token) {
        return { Authorization: `Bearer ${user.token}` };
    } else {
        return {};
    }
};

const doctorService = {
    // 医生接口
    getDoctorProfile,
    updateDoctorProfile,
    
    // 管理员接口
    getAllDoctors,
    getDoctorById,
    createDoctor,
    updateDoctor,
    deleteDoctor,
    getDoctorsByDepartment
};

export default doctorService; 